import axios from 'axios'
import {
  Loading
} from 'element-ui';
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant';
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
const service = axios.create();
const controller = new AbortController()
//加载图案
var loadingInstance
service.interceptors.request.use((config) => {
  // 加载效果
  loadingInstance = Loading.service({
    text: '加载中...'
  });
  //判断是否需要发送token
  if (config.headers.token) {
    if (!store.state.user.token) {
      //取消请求
      config.signal = controller.signal
      controller.abort()
      Toast('请先登录')
      router.push({
        name: 'login'
      })
      return config
    }
    config.headers.authorization = store.state.user.token
  }
  return config;
}, (error) => {
  console.log(error);
});

// 添加响应拦截器
service.interceptors.response.use((response) => { //根据状态码做判断
  let res = {}
  res.status = response.status
  res.data = response.data
  //token错误信息
  if(res.data.code === 400){
    store.commit('loginOut')
  }
  //结束加载效果
  loadingInstance.close()
  return res;
}, (error) => {
  // 对响应错误做点什么
  loadingInstance.close()
});

export default service
